package com.antgroup.seckill.business.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import sun.misc.BASE64Encoder;

import javax.crypto.SecretKey;

import java.util.Date;

/**
 * @author wangxy
 * @date 2024/7/28 10:48
 */
public class JwtUtil {


    private static final String SECRET_KEY = " maPiHCjlny4+CQEAYAoQYae+fgojD/c6+LsvraeZCPY=";
    private static final long EXPIRATION_TIME = 86400000; // 1 day in milliseconds

    public static String generateToken(String username) {
        return Jwts.builder()
                .setSubject(username)
                .setExpiration(new Date(System.currentTimeMillis() + SecretKeyGeneratorUtil.generateSecretKey()))
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
    }

    public static String getUserNameFromToken(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(SecretKeyGeneratorUtil.generateSecretKey())
                .parseClaimsJws(token)
                .getBody();
        return claims.getSubject();
    }

    public static boolean validateToken(String token) {
        try {
            Jwts.parser().setSigningKey(SecretKeyGeneratorUtil.generateSecretKey()).parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static void main(String[] args) {
        String key = "1234567890_1234567890_1234567890";
        //对秘钥做bse64编码
        String base64 = new BASE64Encoder().encode(key.getBytes());

        //生成秘钥对象
        SecretKey secretKey = Keys.hmacShaKeyFor(base64.getBytes());

        //利用jjwt生成Token
        String data = "{\"nickName\":\"不然\"}";

        String s = Jwts.builder().setSubject(data).signWith(SignatureAlgorithm.HS256,secretKey).compact();
        System.out.println(s);

        String s1 = generateToken(data);
        System.out.println(s1);

        String userNameFromToken = getUserNameFromToken("eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ7XCJuaWNrTmFtZVwiOlwi5LiN54S2XCJ9IiwiZXhwIjoxNzIyMjQwMjQwfQ.S0Uq0AqaXtV11mOvYveaeHtqD2S-MDSYYqo3r9-1LPA");
        System.out.println(userNameFromToken);


    }
}
